//
//  JZReleaseCapterViewController.m
//  jz_sanrenxing
//
//  Created by GuJun on 16/10/9.
//  Copyright © 2016年 杭州景忠网络科技有限公司. All rights reserved.
//

#import "JZReleaseCapterViewController.h"
#import "JZCourseConditionsTableViewCell.h"
#import "UserInfoTableView.h"
#import "SZCalendarPicker.h"
#import "YKUploaderEngine.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AFNetworking/AFNetworking.h>

@interface JZReleaseCapterViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UserInfoTableViewDelegate,UIImagePickerControllerDelegate,YKUploaderEngineDelegate,UINavigationControllerDelegate>{
    
    UITextField *_cellTextField;
    NSString    *_videoPath;
    NSURL       *_VideoUrl;
    
}

@property (weak, nonatomic) IBOutlet UserInfoTableView *CapterTableview;

@property (weak, nonatomic) IBOutlet UITextField       *CapterBrifTextfield;

@property (weak, nonatomic) IBOutlet UITextField       *CapterOpenDateTextfield;

@property (weak, nonatomic) IBOutlet UITextField       *CapterOpenTimeTextfield;

@property (strong, nonatomic) IBOutlet UIView          *CapterFooterView;

@property (nonatomic, strong) NSArray                  *conditionsArray;

@property (nonatomic, strong) NSMutableDictionary      *diccc;

@property (weak, nonatomic) IBOutlet UIImageView       *ClickImgeTap;

@property (nonatomic, strong) UIImagePickerController  *videoPicker;


- (IBAction)clickOpenDateButton:(UIButton *)sender;

@end

@implementation JZReleaseCapterViewController

- (NSArray *)conditionsArray{
    
    if (!_conditionsArray) {
        _conditionsArray = [NSArray arrayWithObjects:@"章节名称",@"关键字", nil];
    }
    return _conditionsArray;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"添加章节";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveCapter)];
    
    //存储tableviewcell的textfield的text的字典
    self.diccc = [NSMutableDictionary dictionary];
    
    self.CapterTableview.tableFooterView = self.CapterFooterView;
    
    self.CapterTableview.separatorStyle  = UITableViewCellSeparatorStyleNone;
    
    self.CapterTableview.touchDelegate = self;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadVideo)];
    
    [_ClickImgeTap addGestureRecognizer:tap];
    
    //优酷
    YKUploaderEngine *uploader = [YKUploaderEngine shareInstance];
    uploader.delegate = self;
    uploader.clientId = @"96a934759cae577a";
    uploader.clientSecret = @"3e9e6f74dbbbbde2e5adea950ba07f76";
    uploader.accessToken = @"65250ca9a7041e6fe9d6d58e3a045691";
    uploader.refreashToken = @"dff6511ec8871bfb585b0e85787bc5df";
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)saveCapter{
    
    //发布章节接口
    [HttpUtils UploadCapterWithPart_name:[NSString stringWithFormat:@"%@",[_diccc objectForKey:@"value0"]]
                               course_id:self.courseModel.course_id
                                part_url:_VideoUrl
                              part_brief:self.CapterBrifTextfield.text
                            part_keyword:[NSString stringWithFormat:@"%@",[_diccc objectForKey:@"value1"]]
                                callback:^(int code, NSDictionary *dict, NSString *msg) {
                                    
                                    if (1 == code) {
                                        
                                        [SVProgressHUD showInfoWithStatus:msg];
                                        
                                    } else {
                                        [SVProgressHUD showInfoWithStatus:msg];
                                    }
                                    
                                }];
    
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  
        return 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        JZCourseConditionsTableViewCell *cell = [JZCourseConditionsTableViewCell TableViewCellWithTableView:tableView];
        cell.title.text = self.conditionsArray[indexPath.row];
        
        _cellTextField = cell.textfield;
        
        cell.textfield.delegate = self;
        
        cell.textfield.tag = indexPath.row + 100;
        
        
        [cell.textfield addTarget:self action:@selector(textFiled:) forControlEvents:UIControlEventAllEditingEvents];
        
        cell.textfield.text = _diccc[[NSString stringWithFormat:@"value%ld", (long)cell.textfield.tag]];
        
        
        return cell;
        
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


//保存数据
- (void)textFiled:(UITextField*)field {
    
    [_diccc setObject:field.text forKey:[NSString stringWithFormat:@"value%ld", (long)field.tag]];;
    
}

- (void)touchTableView {
    [_cellTextField resignFirstResponder];
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)clickOpenDateButton:(UIButton *)sender {
    
    SZCalendarPicker *calendarPicker = [SZCalendarPicker showOnView:self.view];
    calendarPicker.today = [NSDate date];
    calendarPicker.date = calendarPicker.today;
    calendarPicker.frame = CGRectMake(0, 100, self.view.frame.size.width, 352);
    calendarPicker.calendarBlock = ^(NSInteger day, NSInteger month, NSInteger year){
        
        NSLog(@"%li-%li-%li", (long)year,(long)month,(long)day);
        
        if (sender.tag == 1000) {
            self.CapterOpenDateTextfield.text = [NSString stringWithFormat:@"%li-%li-%li",(long)year,(long)month,(long)day];
        }else{
            self.CapterOpenDateTextfield.text = [NSString stringWithFormat:@"%li-%li-%li",(long)year,(long)month,(long)day];
        }
    };
}


- (void)uploadVideo{
    
    if ([_diccc count] == 0 ) {
        [SVProgressHUD showInfoWithStatus:@"请先填写章节名称和关键字"];
    }else{
        _videoPicker = [[UIImagePickerController alloc] init];
        _videoPicker.delegate = self;
        _videoPicker.allowsEditing = YES;
        _videoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _videoPicker.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeMovie ,nil];
        [self presentViewController:_videoPicker animated:YES completion:^{
            NSLog(@"picker start!");
        }];
    }
    
}

#pragma mark   YKUploaderEngineDelegate

- (void)uploaderEngineDidError:(NSDictionary *)errors
{
    NSLog(@"error info:%@",errors);
}

- (void)uploaderEngineDidCreate:(NSString *)videoid
{
    NSString *createText = [NSString stringWithFormat:@"%@开始上传",videoid];
    
    NSLog(@"create videoid:%@",createText);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 设置请求格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    // 设置返回格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *url = @"https://openapi.youku.com/v2/videos/show.json";
    
    NSDictionary *dict = @{
                           @"video_id":videoid,
                           @"client_id":@"96a934759cae577a"
                           };
    [manager GET:url parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"JSON解析异常");
            NSLog(@"请求失败的URL:%@",task.currentRequest.URL.absoluteString);
        } else {
            NSLog(@"%@",result);
            _VideoUrl = [NSURL URLWithString:result[@"link"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误 %@", error.localizedDescription);
    }];

}

- (void)uploaderEngineDidUpdateToken:(NSDictionary *)tokens
{
    NSLog(@"update tokens:%@",tokens);
}

- (void)uploaderEngineDidProgress:(NSInteger)progress
{
    
    NSLog(@"upload progress:%ld",(long)progress);
}

- (void)uploaderEngineDidSuccesss:(NSString *)videoid
{
    NSString *createText = [NSString stringWithFormat:@"%@上传完成",videoid];
   
    NSLog(@"commit videoid:%@",createText);
    
}


#pragma mark  UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSLog(@"picker cancel");
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *videoUrl = [info objectForKey:UIImagePickerControllerReferenceURL];
        [self saveVideoWithUrl:videoUrl fileName:@"testVideo1.mov"];
        _ClickImgeTap.image = [self thumbnailImageForVideo:videoUrl atTime:1.0];
    }
    
    [picker dismissViewControllerAnimated:YES completion:^{
        NSLog(@"picker controller ok");
    }];}

- (void)saveVideoWithUrl:(NSURL *)url fileName:(NSString *)filename
{
    NSLog(@"video url:%@",url.absoluteString);
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (url) {
            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
                ALAssetRepresentation *rep = [asset defaultRepresentation];
                NSString *vPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/%@",filename];
                NSFileManager * fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:vPath]) {
                    [fileManager removeItemAtPath:vPath error:nil];
                }
                NSLog(@"video path:%@",vPath);
                const char *videoPath = [vPath UTF8String];
                FILE *file = fopen(videoPath, "a+");
                if (file) {
                    const int bufferSize = 2 * 1024 * 1024;
                    Byte *buffer = (Byte*)malloc(bufferSize);
                    NSUInteger read = 0, offset = 0, written = 0;
                    NSError* err = nil;
                    if (rep.size != 0) {
                        do {
                            read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];
                            written = fwrite(buffer, sizeof(char), read, file);
                            offset += read;
                        } while (read != 0 && !err);
                    }
                    free(buffer);
                    buffer = NULL;
                    fclose(file);
                    file = NULL;
                    
                    if (![fileManager fileExistsAtPath:vPath]) {
                        [fileManager createDirectoryAtPath:vPath withIntermediateDirectories:YES attributes:nil error:nil];
                    }
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    
                    [params setObject:vPath forKey:@"file_name"]; //文件名
                    [params setObject:[_diccc objectForKey:@"value0"] forKey:@"title"]; // 标题
                    [params setObject:[_diccc objectForKey:@"value1"] forKey:@"tags"];  // 标签
                    // 视频公开类型（all：公开（默认） friend：仅好友 password：加密）
                    [params setObject:@"all" forKey:@"public_type"];
                    //密码，当public_type为passowrd时必选参数
                    //                    [params setObject:@"123456" forKey:@"watch_password"];
                    
                    [YKUploaderEngine shareInstance].uploadParams = [NSDictionary dictionaryWithDictionary:params];
                    [[YKUploaderEngine shareInstance] upload];
                }
            } failureBlock:nil];
        }
    });
}

//获取视频第一帧图片
- (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    return thumbnailImage;
}


@end
